<template>

  <view>
    <view v-if="openid==''" style="text-align: center;">
      <u-loading mode="circle"></u-loading>
    </view>
    <view v-if="openid!=''">
      <view class="order-price-view">
        <view>
          <custom-price class="u-margin-top-30" :price="order.need_pay_price" :size="60" :fontWeight="400">
          </custom-price>
          <view>
            <text class="times-title">支付剩余时间</text>
            <u-count-down :timestamp="orderForm.cancel_order_day*24*60*60" :show-days="false"></u-count-down>
          </view>
        </view>
      </view>

      <view class="payment-view u-margin-top-30">
        <view class="u-p-25">
          <u-checkbox active-color="#FD5B00" v-model="isCheckPreDeposit" shape="square">
            <view class="u-m-l-10 u-font-24">
              <text
                style="font-size: 30rpx;font-weight: 700;">使用代金券支付（代金券余额￥{{account_balance | unitPrice}}，目前需在线支付￥{{ order.need_pay_price | unitPrice}}）</text>
              <text @click="handleRecharge" v-if="account_balance == 0 && unitPrice==0">余额不足？马上充值</text>
            </view>
          </u-checkbox>
          <view class="" v-if="isCheckPreDeposit">
            <u-message-input active-color="#FD5B00" :maxlength="6" :dot-fill="true" @finish="handlePasswordFinish">
            </u-message-input>
            <view class="tip-box">
              <view class="u-flex">
                <u-icon size="36" name="error-circle-fill"></u-icon>
                <text class="u-font-24 u-m-l-10">支付密码与用户登录密码不同，可在用户中心进行设置</text>
              </view>
              <navigator class="tip" url="/mine-module/account-safe"
                v-if="order&&order.deposite&&!order.deposite.is_pwd">您还未设置支付密码?</navigator>
              <navigator class="tip" url="/mine-module/account-safe" v-else>忘记密码?</navigator>
            </view>
          </view>
        </view>
      </view>



      <view class="payment-view u-margin-top-30">
        <view class="u-flex u-row-between u-p-25" :class="index > 0 ? 'cell-view' : '' "
          @click="handlePaymentType(pay.plugin_id)" v-for="(pay, index) in paymentList" :key="index">
          <view class="cell-icon">
            <u-image width="60" height="60" :src="pay.image"></u-image>
          </view>
          <view class="cell-title">
            {{ pay.method_name }}
          </view>
          <view class="cell-right-icon">
            <u-icon :name="pay.selected ? 'xuanze' : 'choose'" custom-prefix="custom-icon"></u-icon>
          </view>
        </view>
      </view>
      <view class="big-btn" @click="$u.debounce(initiatePay, 1500)" v-if="!isCheckPreDeposit">
        <view class="btn u-flex u-row-center">
          确认支付
          <custom-price :price="order.need_pay_price" :textColor="'#FFFFFF'"></custom-price>
        </view>
      </view>



      <!-- #ifdef H5 -->
      <div class="__pay_form__"></div>
      <!-- #endif -->
      <view v-if="debug">{{log}}</view>
    </view>
  </view>
</template>

<script>
  import * as API_Trade from '@/api/trade.js'
  import * as Payment from '@/common/payment.js'
  import * as API_Deposit from '@/api/deposit.js'
  import * as Openid from '@/api/openid.js'
  import {
    getUrlParam,
    getCodeApi,
    isWeixin
  } from '@/utils/wx.js'
  import Cache, {
    Keys
  } from '@/utils/cache.js';

  export default {
    data() {
      return {
        debug: false, //在app里显示调试日志
        openid: '',
        log: 'log',
        trade_sn: '',
        order_sn: '', //订单编号
        order: '', //订单详情
        is_callback: '', //是否是支付跳转回来的，如果为yes，表示是跳转回来的
        default_plugin_id: '', //默认要选中的支付方式
        paymentList: [], //支付方式列表
        payment_plugin_id: '', //支付方式
        account_balance: 0, //代金券余额
        isCheckPreDeposit: false, //是否使用代金券支付
        /** 订单设置 */
        orderForm: {
          cancel_order_day: 1,
          rog_order_day: 10,
          comment_order_day: 15,
          service_expired_day: 30,
          complain_expired_day: 30,
          complete_order_day: 7,
          complete_order_pay: 3
        },
        insurance: 0,
        process: 0,
        sn: '',
        isZhifu: false,
      };
    },
    async onLoad(options) {
      setTimeout(() => {
        console.log(this.paymentList)
      }, 5000)
      if (options.insurance) this.insurance = Number(options.insurance)
      if (options.process) this.process = Number(options.process)
      if (options.sn) this.sn = options.sn
      this.trade_sn = options.trade_sn || ''
      this.order_sn = options.order_sn || ''
      this.is_callback = options.is_callback || ''
      this.default_plugin_id = options.default_plugin_id || ''
      this.openid = Cache.getItem(Keys.wxopenid);
      if (this.is_callback == 'yes') {
        this.payCallback()
      }

      // #ifdef APP-PLUS
      this.openid = 'appopenid'
      this.loadPaymentList()
      // #endif

      // #ifdef H5
      let code = options.code || ''
      this.loadH5OpenId(code)
      // #endif

      // // #ifdef H5
      // if (isWeixin()) {
      //   let localOpenId = uni.getStorageSync("openid");
      //   console.log('openid', localOpenId)
      //   if (!localOpenId) {
      //     this.getCode();
      //   }
      // }
      // // #endif


      // #ifdef MP-WEIXIN
      this.loadMiniOpenId()
      // #endif

      this.getTradeSetting()

      this.memberPrepay()
    },
    watch: {
      isCheckPreDeposit(val) {
        if (!val) return
        this.paymentList.forEach(item => {
          item.selected = false
        })
      }
    },
    methods: {
      memberPrepay() {
        let res = API_Trade.memberPrepay(this.sn || this.order_sn).then(res => {
          console.log('付款前检查', res)
          this.isZhifu = res
        }).catch(err => {
          uni.showToast({
            icon: 'none',
            title: err.data.message,
            duration: 5000,
            mask: true,
          })
          setTimeout(() => {
            uni.switchTab({
              url: '/pages/tabs/home/home'
            })
          }, 5000)
        })
      },
      getCode() {
        const code = getUrlParam("code");
        console.log('查看code', code)
        if (code == null || code === "") {
          let localOpenId = uni.getStorageSync("openid");
          if (!localOpenId) {
            getCodeApi();
          }
        } else {
          this.getOpenId(code);
        }
      },
      getOpenId(code) {
        Openid.fetchWeiXinH5OpenId(code).then(openid => {
          uni.setStorageSync('openid', openid)
        })
      },

      // 获取订单设置数据
      getTradeSetting() {
        API_Trade.getTradeSetting().then(response => {
          Object.keys(this.orderForm).forEach(key => {
            this.orderForm[key] = response[key]
          })
        })
      },
      //马上充值
      handleRecharge() {
        uni.navigateTo({
          // url:"/mine-module/account-balance"
          url: "/mine-module/chongzhi/paymentmobile"
        })
      },
      //支付密码输入结束
      handlePasswordFinish(password) {
        if (Number(this.order.need_pay_price) > Number(this.account_balance)) return this.$u.toast('代金券不足，请充值')
        const trade_type = this.trade_sn ? 'TRADE' : 'ORDER'
        const sn = this.trade_sn || this.order_sn
        const params = {
          sn,
          trade_type,
          password
        }
        console.log(password)
        API_Deposit.getBalancePay(trade_type, sn, params).then(response => {
          if (response.need_pay == 0) {
            uni.redirectTo({
              url: "/pages/payment-complete/payment-complete"
            })
          } else {
            this.isCheckPreDeposit = false
            this.password = ''
            this.loadPaymentList()
          }
        })
      },
      loadMiniOpenId() {
        if (this.openid == '') {
          Openid.fetchWeixinMiniOpenId().then(openid => {
            this.openid = openid
            this.loadPaymentList()
          }).catch(e => {
            this.$u.toast(`获取openid出现意外错误`)
          })
        } else {
          this.loadPaymentList()
        }
      },
      loadH5OpenId(code) {

        //非微信内部，跳过获取openid
        if (!this.is_weixin()) {
          this.openid = "h5openid"
        }
        if (this.openid == '') {

          console.log("code is " + code)
          if (code == '') {
            Openid.createRedirectUri().then(url => {

              location.href = url;
            });
          } else {
            Openid.fetchWeiXinH5OpenId(code).then(openid => {
              this.openid = openid
              this.loadPaymentList()
            })
          }

        } else {
          this.loadPaymentList()
        }
      },
      is_weixin() {
        let ua = navigator.userAgent.toLowerCase();
        if (ua.match(/MicroMessenger/i) == "micromessenger") {
          return true;
        } else {
          return false;
        }
      },
      loadPaymentList() {
        let that = this
        // #ifdef APP-PLUS
        const client_type = 'NATIVE'
        // #endif
        // #ifdef H5
        const client_type = 'WAP'
        // #endif
        // #ifdef MP
        const client_type = 'MINI'
        // #endif
        Promise.all([
          this.trade_sn ?
          API_Trade.getCashierData({
            trade_sn: this.trade_sn
          }) :
          API_Trade.getCashierData({
            order_sn: this.order_sn
          }),
          API_Trade.getPaymentList(client_type),
          API_Deposit.getDepositBalance()
        ]).then(response => {
          // response[0].need_pay_price += (that.insurance + that.process)
          this.order = response[0];
          console.log('查看订单', this.order)
          this.account_balance = response[2];
          // this.account_balance = 0

          if (response[1] && response[1].length) {
            // 默认不选中支付方式
            response[1].forEach(item => {
              item.selected = false;
              //如果传递了default_plugin_id则选中此支付方式
              if (item.plugin_id == this.default_plugin_id) {
                item.selected = true;
              }
            })
            this.paymentList = response[1];
            // #ifndef MP-WEIXIN
            // 如果是在微信浏览器内则隐藏支付宝支付
            if (this.is_weixin()) {
              this.paymentList = this.paymentList.filter(item => item.plugin_id !== 'alipayDirectPlugin');
            }
            // #endif

            // 如果是在小程序内则隐藏支付宝支付
            // #ifdef MP-WEIXIN
            console.log('this is MP-WEIXIN')
            this.paymentList = this.paymentList.filter(item => item.plugin_id !== 'alipayDirectPlugin')
            // #endif
          }

          if (this.default_plugin_id == '') {
            // #ifdef  APP-PLUS
            this.paymentList[0].selected = true
            // #endif
            this.payment_plugin_id = this.paymentList[0].plugin_id
          } else {
            this.payment_plugin_id = this.default_plugin_id
          }

        })
      },
      //选择支付方式
      handlePaymentType(plugin_id) {
        this.isCheckPreDeposit = false
        this.paymentList.forEach(item => {
          item.selected = false
          if (item.plugin_id === plugin_id) {
            item.selected = true
          }
        })
        this.payment_plugin_id = plugin_id
      },
      payCallback() {
        uni.showModal({
          title: '支付提示',
          content: '请确认支付是否完成',
          confirmText: '支付成功',
          cancelText: '重新支付',
          success(res) {
            if (res.confirm) {
              uni.redirectTo({
                url: '/pages/order/order-list'
              })
            }
          }
        })
      },
      payFail(err) {
        if (this.debug) {
          this.log = 'fail:' + JSON.stringify(err)
        }
      },

      //判断是安卓还是ios
      isAndroid() {
        switch (uni.getSystemInfoSync().platform) {
          case 'android':
            return true;
          case 'ios':
            return false;
          default:
            console.log('运行在开发者工具上')
            break;
        }
      },
      launchMini(item) {
        // #ifdef H5
        let url = item.qrData
        if (item.browser == "alipay") {
          url = 'alipayqr://platformapi/startapp?saId=10000007&clientVersion=3.7.0.0718&qrcode=' + url
          console.log('广东快付支付宝', url)
        } else if (item.browser == "wxpay") {
          console.log('广东快付微信', url)
        }
        window.location.href = url
        //#endif

        // #ifdef APP-PLUS
        if (item.browser == "alipay") {
          plus.runtime.openURL('alipayqr://platformapi/startapp?saId=10000007&clientVersion=3.7.0.0718&qrcode=' + item
            .qrData)
          console.log('广东快付支付宝')
        } else if (item.browser == "wxpay") {
          uni.setStorageSync('qrData', item.qrData)
          uni.navigateTo({
            url: '/pages/cashier/testH5'
          });
        }
        return

        // 如果是ios 需要先login 然后在 执行下面的代码 isIOS 这个方法根据你项目中的来定义 即可
        if (!this.isAndroid()) {
          uni.login({
            provider: 'weixin',
            success: function(loginRes1) {
              plus.share.getServices(function(res) {
                var sweixin = null;
                for (var i = 0; i < res.length; i++) {
                  var t = res[i];
                  if (t.id == 'weixin') {
                    sweixin = t;
                  }
                }

                if (sweixin) {
                  sweixin.launchMiniProgram({
                    id: 'gh_5ef9306a314f',
                    // path: 'pages/index/index?orderCd=26ecbf3363bd4f0b9f9ac39636f179b5&sign=d5606d24a4a5fa20a9d5cc91d2c1b482',
                    path: `pages/index/index?orderCd=${item.orderCd}&sign=${item.sign}`,
                    type: 0
                  });
                }
              }, function(res) {
                console.log(JSON.stringify(res));
              });
            }
          });
        } else {
          plus.share.getServices(function(res) {
            var sweixin = null;
            for (var i = 0; i < res.length; i++) {
              var t = res[i];
              if (t.id == 'weixin') {
                sweixin = t;
              }
            }

            if (sweixin) {
              sweixin.launchMiniProgram({
                id: 'gh_5ef9306a314f',
                path: `pages/index/index?orderCd=${item.orderCd}&sign=${item.sign}`,
                type: 0
              });
            }
          }, function(res) {
            console.log(JSON.stringify(res));
          });
        }
        //#endif
      },
      //确定支付
      async initiatePay() {
        if (!this.isZhifu) {
          return this.$u.toast('检查支付失败，请重试')
        }

        if (this.openid == 'error') {
          this.$u.toast(`openid不正确，不能支付`)
          return
        }
        if (!this.paymentList.some(item => item.selected)) {
          this.$u.toast(`请选择支付方式`)
          return
        }
        const trade_type = this.trade_sn ? 'TRADE' : 'order'
        // const trade_type = 'ORDER'
        const sn = this.trade_sn || this.order_sn
        // const sn = this.sn
        const openid = this.openid;
        // #ifdef APP-PLUS
        const client_type = 'NATIVE'
        // #endif

        // #ifdef H5
        const client_type = 'WAP'
        // const client_type = 'NATIVE'
        // #endif


        // #ifdef MP
        const client_type = 'MINI'
        // #endif

        const pay_mode = 'normal'
        const payment_plugin_id = this.payment_plugin_id
        const that = this

        // #ifdef H5
        const uni_app = 'H5'
        // #endif

        // #ifndef H5
        const uni_app = 'UNH5'
        // #endif



        // #ifdef H5
        //非微信内部，跳过获取openid
        if (!this.is_weixin() && this.payment_plugin_id == 'weixinPayPlugin') {
          return this.$u.toast('请通过微信直接打开链接再支付')
        }
        // #endif

        let pay_params = {
          client_type,
          pay_mode,
          uni_app,
          payment_plugin_id,
          openid
        }

        console.log('查看支付参数', trade_type, sn, pay_params)
        if (payment_plugin_id === 'fastPayMiniPlugin') {
          return this.openMini(sn, pay_params)
        }

        API_Trade.initiatePay(trade_type, sn, pay_params).then(response => {
          console.log(response)
          // return
          if (payment_plugin_id === 'weixinPayPlugin') {
            //微信内嵌H5，调用wechatH5Pay方法
            // #ifdef H5
            if (typeof WeixinJSBridge == "undefined") {
              Payment.mobileH5Pay(response, this.payCallback, this.payFail)
            } else {
              Payment.wechatH5Pay(response, this.payCallback, this.payFail)
            }
            // #endif

            //微信小程序，调用wechatMiniPay方法
            // #ifdef MP-WEIXIN
            Payment.wechatMiniPay(response, this.payCallback, this.payFail)
            // #endif

            //微信App
            // #ifdef APP-PLUS
            Payment.wechatAppPay(response, this.payCallback, this.payFail)
            // #endif

            // } else if (typeof response.gateway_url == 'string') {
            //   // } else if (payment_plugin_id === 'fastpayPlugin') {
            //   let obj = JSON.parse(response.gateway_url)
            //   console.log(obj)
            //   this.launchMini(obj)

          } else {

            // #ifdef H5
            //调起支付宝支付
            Payment.aliPayH5(response, this.payCallback, this.payFail)
            // #endif

            // #ifdef APP-PLUS
            Payment.aliPayApp(response, this.payCallback, this.payFail)
            // #endif

          }

        })
      },


      openMini(sn, pay_params) {
        console.log(sn, pay_params)
        // #ifdef APP-PLUS
        // 如果是ios 需要先login 然后在 执行下面的代码 isIOS 这个方法根据你项目中的来定义 即可
        if (!this.isAndroid()) {
          uni.login({
            provider: 'weixin',
            success: function(loginRes1) {
              plus.share.getServices(function(res) {
                var sweixin = null;
                for (var i = 0; i < res.length; i++) {
                  var t = res[i];
                  if (t.id == 'weixin') {
                    sweixin = t;
                  }
                }

                if (sweixin) {
                  let path =
                    // `pages/test/test?openid=${that.openid}&num=${that.price}&out_trade_no=${that.ordersn}&goodstitle=${that.title}&type=pay`
                    `pages/test/test?sn=${sn}&type=goods&token=${uni.getStorageSync('accessToken')}`
                  sweixin.launchMiniProgram({
                    id: 'gh_3e1ea12cfb44',
                    path: path,
                    type: 0, //可取值： 0-正式版； 1-测试版； 2-体验版。 默认值为0。
                  });
                }
              }, function(res) {
                console.log(JSON.stringify(res));
              });
            }
          });
        } else {
          plus.share.getServices(function(res) {
            var sweixin = null;
            for (var i = 0; i < res.length; i++) {
              var t = res[i];
              if (t.id == 'weixin') {
                sweixin = t;
              }
            }
            console.log(sweixin)
            if (sweixin) {
              let path =
                // `pages/test/test?openid=${that.openid}&num=${that.price}&out_trade_no=${that.ordersn}&goodstitle=${that.title}&type=pay`
                `pages/test/test?sn=${sn}&type=goods&token=${uni.getStorageSync('accessToken')}`
              sweixin.launchMiniProgram({
                id: 'gh_3e1ea12cfb44',
                path: path,
                type: 0, //可取值： 0-正式版； 1-测试版； 2-体验版。 默认值为0。
              });
            }
          }, function(res) {
            console.log(JSON.stringify(res));
          });
        }
        //#endif
      },
    }
  }
</script>

<style lang="scss">
  .order-price-view {
    background-color: #FFFFFF;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 50rpx;
    text-align: center;

    .order-price {
      font-size: 45rpx;
      color: #FD5B00;
      font-weight: bold;
    }

    .times-title {
      margin: 0rpx 10rpx;
    }
  }

  .payment-view {
    margin: 20rpx;
    border-radius: 20rpx;
    background-color: #FFFFFF;

    .cell-view {
      border-top: 2rpx solid #E5E5E5;
    }

    .cell-icon {
      padding: 10rpx 0rpx;
    }

    .cell-title {
      text-align: right;
      flex: 1;
      margin: 0 20rpx;
      font-size: 30rpx;
      font-weight: bold;
    }
  }

  .tip-box {
    padding-left: 20rpx;
    margin-top: 20rpx;
    color: #ffcc00;

    .tip {
      display: inline-block;
      background-color: #F59C1A;
      border-color: #F59C1A;
      color: #FFF;
      padding: 8rpx 16rpx;
      border-radius: 10rpx;
      margin: 20rpx 0 0 10rpx;
      font-size: 24rpx;
    }
  }

  /deep/ {
    .custom-icon-xuanze {
      color: #FD5B00;
      font-size: 40rpx !important;
    }

    .custom-icon-choose {
      font-size: 40rpx !important;
    }
  }
</style>
